package com.xinghanlaser.applet.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xinghanlaser.applet.cache.PhoneCodeCache;
import com.xinghanlaser.applet.service.IPhoneCodeService;
import com.xinghanlaser.applet.utils.SMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/7 11:22
 */
@Service
@Slf4j
public class PhoneCodeServiceImpl implements IPhoneCodeService {
    @Resource
    private SMSUtil smsUtil;

    @Resource
    private PhoneCodeCache phoneCodeCache;

    @Value("${phone-code.type: CONSTANT}")
    private String phoneCodeType;

    @Value("${phone-code.timeout: 300}")
    private Long timeout;

    @Value("${phone-code.length: 300}")
    private Integer codeLength;

    @Override
    public void generateAndSendCode(String phone) {
        // 生成验证码
        String code = generateCode();

        if(!phoneCodeType.equals("CONSTANT")){
            smsUtil.send(phone, code);
        }

        // 保存缓存
        saveCache(phone, code);

        log.info("CODE : " + phone + " : " + code);
    }

    @Override
    public boolean validatedCode(String phone, String code) {
        String codeCache = getCacheCode(phone);

        // 缓存验证码不存在返回错误
        if(StrUtil.isBlank(codeCache)) return false;

        // 判断缓存验证码和提供验证码是否一致
        return codeCache.equals(code);
    }

    @Override
    public void clearCode(String phone) {
        phoneCodeCache.remove(phone);
    }

    private String generateCode(){
        if(phoneCodeType.equals("CONSTANT")){
            return "123456";
        }
        else {
            return RandomUtil.randomNumbers(codeLength);
        }
    }

    private void saveCache(String phone, String code){
        phoneCodeCache.put(phone, code, timeout, TimeUnit.MINUTES);
    }

    private String getCacheCode(String phone){
        return phoneCodeCache.get(phone, String.class);
    }


}
